<template>
  <el-dialog title="仓库选择"
             v-if="showFlag"
             :visible.sync="showFlag"
             :modal="false"
             width="40%"
             center
  >
    <div style="max-height: 500px; overflow-y: auto;">
      <el-tree
          :data="formattedWareHouseList"
          show-checkbox
          node-key="id"
          ref="tree"
          :props="defaultProps"
          @check-change="handleCheckChange"
      ></el-tree>
<!--      <el-button @click="getCheckedNodes">获取选中节点</el-button>-->
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="confirmSelect">确 定</el-button>
      <el-button @click="showFlag = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getTreeList } from '@/api/mes/wm/warehouse';

export default {
  name: "VendorSelect",
  props: {
    itemId: String,
  },
  data() {
    return {
      showFlag: false,
      loading: true,
      showSearch: true,
      total: 0,
      wareHouseList: [],
      formattedWareHouseList: [],
      selectedWareHouses: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enableFlag: 'Y',
      },
      form: {}
    };
  },
  computed: {
    defaultProps() {
      return {
        children: 'children',
        label: 'label',
        id: 'id'
      };
    }
  },
  created() {
    this.getList();
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    getCheckedNodes() {
      const checkedNodes = this.$refs.tree.getCheckedNodes(true);
      console.log('Checked Nodes:', checkedNodes); // 调试信息
      if (checkedNodes.length > 0) {
        this.$message({
          message: `选中的节点: ${JSON.stringify(checkedNodes)}`,
          type: 'success'
        });
      } else {
        this.$message({
          message: '没有选中的节点',
          type: 'warning'
        });
      }
    },
    getList() {
      this.loading = true;
      getTreeList(this.queryParams).then(response => {
        console.log('getTreeList Response:', response); // 调试信息
        if (response && response.data) {
          this.wareHouseList = response.data;
          // this.formattedWareHouseList = this.formatData(this.wareHouseList);
          this.formattedWareHouseList = response.data;
          console.log('formattedWareHouseList:', this.formattedWareHouseList); // 调试信息
        } else {
          console.error('Invalid response format:', response);
          this.formattedWareHouseList = [];
        }
        this.loading = false;
      }).catch(error => {
        console.error('Error fetching data:', error);
        this.loading = false;
      });
    },
    formatData(data) {
      return data.filter(item => {
        item.id = this.getIdKey(item);
        item.label = this.getLabelKey(item);
        if (item.children && item.children.length > 0) {
          item.children = this.formatData(item.children);
        }

        // 过滤掉没有子节点的节点
        return !!item.label && (item.children && item.children.length > 0 || !item.children);
      });
    },
    getLabelKey(data) {
      switch (data.nodeType) {
        case 'warehouse':
          return data.warehouseName;
        case 'location':
          return data.locationName;
        case 'area':
          return data.areaName;
        default:
          return '';
      }
    },
    getIdKey(data) {
      console.log('--getIdKey data--',data);
      switch (data.nodeType) {
        case 'warehouse':
          return data.warehouseId;
        case 'location':
          return data.locationId;
        case 'area':
          return data.areaId;
        default:
          return '';
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    findParentInfo(node, allNodes) {
      let parent = null;
      for (let i = 0; i < allNodes.length; i++) {
        const currentNode = allNodes[i];
        if (currentNode.children && currentNode.children.includes(node)) {
          parent = currentNode;
          break;
        } else if (currentNode.children) {
          parent = this.findParentInfo(node, currentNode.children);
          if (parent) break;
        }
      }
      return parent;
    },
    confirmSelect() {
      const checkedNodes = this.$refs.tree.getCheckedNodes(true);
      console.log('----confirmSelect checkedNodes',checkedNodes);
      if (checkedNodes.length === 0) {
        this.$notify({
          title: '提示',
          type: 'warning',
          message: '请至少选择一条数据!'
        });
        return;
      }
/*      this.selectedWareHouses = checkedNodes.map(node => (
          {
        areaId: node.areaId || '',
        areaCode: node.areaCode || '',
        areaName: node.areaName || '',
        locationId: node.locationId || '',
        locationCode: node.locationCode || '',
        locationName: node.locationName || '',
        warehouseId: node.warehouseId || '',
        warehouseCode: node.warehouseCode || '',
        warehouseName: node.warehouseName || ''
      }));*/
      this.selectedWareHouses = checkedNodes.map(node => {
        const result = {
          areaId: node.areaId || '',
          areaCode: node.areaCode || '',
          areaName: node.areaName || '',
          locationId: node.locationId || '',
          locationCode: node.locationCode || '',
          locationName: node.locationName || '',
          warehouseId: node.warehouseId || '',
          warehouseCode: node.warehouseCode || '',
          warehouseName: node.warehouseName || ''
        };

        let currentParent = node;
        while (currentParent) {
          const parent = this.findParentInfo(currentParent, this.formattedWareHouseList);
          if (parent) {
            if (parent.nodeType === 'location') {
              result.locationId = parent.locationId || '';
              result.locationCode = parent.locationCode || '';
              result.locationName = parent.locationName || '';
            } else if (parent.nodeType === 'warehouse') {
              result.warehouseId = parent.warehouseId || '';
              result.warehouseCode = parent.warehouseCode || '';
              result.warehouseName = parent.warehouseName || '';
            }
            currentParent = parent;
          } else {
            currentParent = null;
          }
        }

        return result;
      });
      this.$emit('onSelected', this.selectedWareHouses);
      this.showFlag = false;
    }
  }
};
</script>

